package com.knife.tools;

import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Calendar;
import java.util.Iterator;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;

import com.knife.news.logic.SiteService;
import com.knife.news.logic.impl.SiteServiceImpl;
import com.knife.news.object.Site;
import com.knife.util.CommUtil;
import com.knife.web.Globals;

public class FileUpload extends HttpServlet {

    private static final long serialVersionUID = 1L;
	private SiteService siteDAO = new SiteServiceImpl();
    private String uploadPath = ""; // 上传目录
    private String sitePath = ""; // 站点目录
    private String tmpPath = ""; // 临时目录
    //private File tempPath; // 用于存放临时文件的目录
    //private String uploadName ="";
    private String filext="";

    @SuppressWarnings("rawtypes")
	@Override
    public void doPost(HttpServletRequest req, HttpServletResponse res)
            throws ServletException, IOException {
        res.setContentType("text/html; charset=UTF-8");
        String uploadType="";
        int fn = CommUtil.null2Int(req.getParameter("CKEditorFuncNum"));
        PrintWriter out = res.getWriter();
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(4096);
        factory.setRepository(new File(tmpPath));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setSizeMax(20480000);
        try {
        	//uploadType=CommUtil.null2String(req.getParameter("rtype"));
        	String sid = CommUtil.null2String(req.getParameter("sid"));
        	String upload_subdir=CommUtil.null2String(req.getParameter("type"));
        	if(upload_subdir.length()==0){
        		upload_subdir="images";
        	}
			Site site = new Site();
			if(sid.length()>0){
				site = siteDAO.getSiteById(sid);
			}else{
				site = siteDAO.getSite();
			}
			sitePath = "/html/"+site.getPub_dir()+"/upload/"+upload_subdir;
			uploadPath = Globals.APP_BASE_DIR + File.separator + "html" + File.separator + site.getPub_dir() + File.separator + "upload"+ File.separator +upload_subdir;
            List fileItems = upload.parseRequest(req);
            Iterator iter = fileItems.iterator();
            String[] errorType = {".exe", ".com", ".cgi", ".asp", ".jsp"};
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                if(item.isFormField() && ((String)item.getFieldName()).equals("rtype"))  
                {  
                	uploadType = item.getString();  
                }

                // 忽略其他不是文件域的所有表单信息
                if (!item.isFormField()) {
                    String name = item.getName();
                    long size = item.getSize();
                    if ((name == null || name.equals("")) && size == 0) {
                        continue;
                    }
                   
                    //判断文件类型
                        for (int temp = 0; temp < errorType.length; temp++) {
                            if (item.getName().endsWith(errorType[temp])) {
                                throw new IOException(name + ": 错误的文件类型");
                            }
                        }
    					filext = FilenameUtils.getExtension(name);
    					if(filext.trim().length()<=0){
    						if(name.lastIndexOf(".")>0){
    							filext=name.substring(name.lastIndexOf(".")+1,name.length());
    						}
    					}
    					UUID uid = UUID.randomUUID();
    					String newfilename = uid.toString() + "." + filext.toLowerCase();
                        
                        String realpath = sitePath + "/" + Calendar.getInstance().get(Calendar.YEAR) + "/"+ (Calendar.getInstance().get(Calendar.MONTH)+1)+"/"+ newfilename;
                        String savepath = uploadPath + File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator
                                + (Calendar.getInstance().get(Calendar.MONTH)+1) + File.separator + newfilename;
                        String pubPath = Globals.APP_BASE_DIR + File.separator + "wwwroot" + File.separator + site.getPub_dir() + File.separator + "upload"+ File.separator +upload_subdir + File.separator + Calendar.getInstance().get(Calendar.YEAR) + File.separator
                                + (Calendar.getInstance().get(Calendar.MONTH)+1) + File.separator + newfilename;
                        try {
                        	File realfile = new File(savepath);
                            // 保存上传的文件到指定的目录
            			    if (!(realfile.getParentFile().exists())){
            			    	realfile.getParentFile().mkdirs();
            			    }
                            item.write(new File(savepath));
    						if(site.getHtml()==1){
    							CopyDirectory.copyFile(realfile, new File(pubPath));
    							if(site.getBig5()==1){
    								String big5Path = savepath.replace(site.getPub_dir() + File.separator + "upload", site.getPub_dir() + File.separator + "big5"+File.separator+"upload");
    								CopyDirectory.copyFile(realfile, new File(big5Path));
    								String big5PubPath = pubPath.replace(site.getPub_dir() + File.separator + "upload", site.getPub_dir() + File.separator + "big5"+File.separator+"upload");
    								CopyDirectory.copyFile(realfile, new File(big5PubPath));
    							}
    						}
    						if("json".equals(uploadType)){
    							out.print("{");
    							out.print("error: '',\n");
    							out.print("msg: '" + realpath + "'\n");
    							out.print("}");
    						}else{
    							out.print("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction('"
                                    + fn
                                    + "','"
                                    + realpath
                                    + "','');</script>");
                            }
                        } catch (Exception e) {
                        	if("json".equals(uploadType)){
    							out.print("{");
    							out.print("error: '',\n");
    							out.print("msg: '上传失败" + e.getMessage() + "'\n");
    							out.print("}");
    						}else{
    							out.print("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction('1','','上传失败," + e.getMessage() + "');</script>");
                            }
                        }
                    }
            }
        } catch (IOException e) {
            //out.println(e);
        	if("json".equals(uploadType)){
				out.print("{");
				out.print("error: '',\n");
				out.print("msg: '上传失败" + e.getMessage() + "'\n");
				out.print("}");
			}else{
				out.print("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction('1','" + e.getMessage() + "','上传失败" + e.getMessage() + "');</script>");
            }
        } catch (FileUploadException e) {
            //out.println(e);
        	if("json".equals(uploadType)){
				out.print("{");
				out.print("error: '',\n");
				out.print("msg: '上传失败" + e.getMessage() + "'\n");
				out.print("}");
			}else{
				out.print("<script type=\"text/javascript\">window.parent.CKEDITOR.tools.callFunction('1','" + e.getMessage() + "','上传失败" + e.getMessage() + "');</script>");
            }
        }
    }

    @Override
    public void init() throws ServletException {
        this.tmpPath = Globals.APP_BASE_DIR + File.separator + "html"+File.separator;
        //到web.xml中的配置文件用于保存上传文件，也可以在已开始定义的时候初始化，不过这样可以通过改动配置文件来改动存放路径，不用改代码，增加了灵活性。
    }
}